//
//  EditSubscibeViewController.m
//  安好
//
//  Created by qinlongqing on 14/12/10.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "EditSubscibeViewController.h"
#import "AppConfig.h"
#import "SubscibeNameListModel.h"


#define kSystemSubscibeLabelSpacingToTop          15
#define kSystemSubscibeButtonSpacingToTop         50

#define kCustomSubscibeLabelSpacingToTop          15
#define kCustomSubscibeButtonSpacingToTop         50
#define kCustomSubscibeTextFieldSpacingToButton   15



@interface EditSubscibeViewController ()<UITextFieldDelegate>
{
    UIScrollView *mainScrollView;
    UIView *systemSubscibeView;
    UIView *mySubscibeView;
    UITextField *customTextField;
    
    NSMutableArray *systemSubscibeArray;
    NSMutableArray *mySubscibeArray;
    
    CGFloat buttonWidth;
    CGFloat buttonHeight;
}
@end

@implementation EditSubscibeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    systemSubscibeArray = [[NSMutableArray alloc]init];
    mySubscibeArray = [[NSMutableArray alloc]init];
    
    [self makeNavBar];

    if (kScreenWidth == 414) {
        buttonWidth = 80;
        buttonHeight = 40;
    }
    else{
        buttonWidth = 66;
        buttonHeight = 33;
    }
    
    //主scrollView
    mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    mainScrollView.scrollEnabled = YES;
    mainScrollView.alwaysBounceVertical = YES;
    mainScrollView.showsVerticalScrollIndicator = YES;
    mainScrollView.backgroundColor = UIColorFromRGB(0xf2f2f2);
    [self.view addSubview:mainScrollView];
    
    //系统的订阅
    systemSubscibeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kSystemSubscibeButtonSpacingToTop)];
    [mainScrollView addSubview:systemSubscibeView];
    
    UILabel *titleLabelSys = [[UILabel alloc]initWithFrame:CGRectMake(15, kSystemSubscibeLabelSpacingToTop, 290, 20)];
    titleLabelSys.backgroundColor = [UIColor clearColor];
    titleLabelSys.font = [UIFont systemFontOfSize:15];
    titleLabelSys.text = @"流行";
    [systemSubscibeView addSubview:titleLabelSys];
    
    //自定义订阅
    mySubscibeView = [[UIView alloc]initWithFrame:CGRectMake(0, 50, kScreenWidth, kScreenHeight - 64 - 50)];
    [mainScrollView addSubview:mySubscibeView];
    
    UILabel *customLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, kCustomSubscibeLabelSpacingToTop, 290, 20)];
    customLabel.backgroundColor=[UIColor clearColor];
    customLabel.font = [UIFont systemFontOfSize:15];
    customLabel.text = @"自定义";
    [mySubscibeView addSubview:customLabel];
    
    customTextField = [[UITextField alloc]initWithFrame:CGRectMake(15, customLabel.frame.origin.y + customLabel.frame.size.height +kCustomSubscibeTextFieldSpacingToButton, kScreenWidth - 30, 40)];
    customTextField.backgroundColor = [UIColor whiteColor];
    customTextField.returnKeyType=UIReturnKeyDone;
    customTextField.placeholder=@"    输入（最多5个字）";
    customTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    customTextField.delegate=self;
    [mySubscibeView addSubview:customTextField];

    [self loadAllSubscibe];
}

-(void)makeNavBar{
    self.navigationItem.title = @"修改订阅";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
//    UIButton *changeSubscibeBTN = [[UIButton alloc]initWithFrame:CGRectMake(240, 24, 80, 35)];
//    [changeSubscibeBTN setTitle:@"完成" forState:UIControlStateNormal];
//    changeSubscibeBTN.titleLabel.font = [UIFont systemFontOfSize:15];
//    [changeSubscibeBTN setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [changeSubscibeBTN addTarget:self action:@selector(doSureToChangeSubscibe) forControlEvents:UIControlEventTouchUpInside];
//    [changeSubscibeBTN sizeToFit];
//    UIBarButtonItem *changeSubscibeButtonItem = [[UIBarButtonItem alloc]initWithCustomView:changeSubscibeBTN];
//    self.navigationItem.rightBarButtonItem = changeSubscibeButtonItem;
}

- (void)backBtnclicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)doSureToChangeSubscibe{
    [self backBtnclicked];
}

- (void)loadAllSubscibe{
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"people":@"0"};
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetAllSubscibeURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
        }
        else{
            NSArray *sysSubscibe = [[responseObject valueForKey:@"data"] valueForKey:@"sys"];
            NSArray *mySubscibe = [[responseObject valueForKey:@"data"] valueForKey:@"my"];
            for (NSInteger i=0; i<sysSubscibe.count; i++) {
                [systemSubscibeArray addObject:[[SubscibeNameListModel alloc]initWithDict:[sysSubscibe objectAtIndex:i]]];
            }
            for (NSInteger i=0; i<mySubscibe.count; i++) {
                [mySubscibeArray addObject:[[SubscibeNameListModel alloc]initWithDict:[mySubscibe objectAtIndex:i]]];
            }
            
            [self reloadSystemAndCustomView];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"网络无法连接，请检查网络" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alertView show];
    }];
}

- (void)reloadSystemAndCustomView{
    [self reloadSystemSubscibeView];
    [self reloadCustomSubscibeView];
    
    if (mySubscibeView.frame.origin.y + mySubscibeView.frame.size.height > kScreenHeight - 64) {
        mainScrollView.contentSize = CGSizeMake(kScreenWidth, mySubscibeView.frame.origin.y + mySubscibeView.frame.size.height);
    }
    else{
        mainScrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight - 64);
    }
}

- (void)reloadSystemSubscibeView{
    for (NSInteger i=0; i<systemSubscibeView.subviews.count; ) {
        if ([[systemSubscibeView.subviews objectAtIndex:i] isKindOfClass:[UIButton class]]) {
            [[systemSubscibeView.subviews objectAtIndex:i] removeFromSuperview];
        }
        else{
            i++;
        }
    }
    for (NSInteger i=0; i<systemSubscibeArray.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = [[[systemSubscibeArray objectAtIndex:i] valueForKey:@"cid"] integerValue];
        NSString *statusStr=[NSString stringWithFormat:@"%@",[[systemSubscibeArray objectAtIndex:i] valueForKey:@"status"]];
        if ([statusStr isEqual:@"1"]) {
            [button setBackgroundImage:[UIImage imageNamed:@"subscribe_select"] forState:UIControlStateNormal];
            [button setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
        }
        else{
            [button setBackgroundImage:[UIImage imageNamed:@"subscribe_unselect"] forState:UIControlStateNormal];
            [button setTitleColor:UIColorFromRGB(0xbababa) forState:UIControlStateNormal];
        }
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button setTitle:[[systemSubscibeArray objectAtIndex:i] valueForKey:@"catname"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(addOrDeleteSystemSubscibeButton:) forControlEvents:UIControlEventTouchUpInside];
        
        NSInteger row = i/4;
        NSInteger col = i%4;
        CGFloat spaceing = (kScreenWidth - buttonWidth*4 - 30)/3;
        button.frame = CGRectMake(15 + (spaceing + buttonWidth)*col, kSystemSubscibeButtonSpacingToTop + (buttonHeight + 12)*row, buttonWidth, buttonHeight);
        [systemSubscibeView addSubview:button];
    }
    NSInteger totalRowForSystem = systemSubscibeArray.count/4;
    if (systemSubscibeArray.count%4) {
        totalRowForSystem += 1;
    }
    systemSubscibeView.frame = CGRectMake(systemSubscibeView.frame.origin.x, systemSubscibeView.frame.origin.y, systemSubscibeView.frame.size.width, kSystemSubscibeButtonSpacingToTop + (buttonHeight + 12)*totalRowForSystem -12);
}

- (void)reloadCustomSubscibeView{
    for (NSInteger i=0; i<mySubscibeView.subviews.count; ) {
        if ([[mySubscibeView.subviews objectAtIndex:i] isKindOfClass:[UIButton class]]) {
            [[mySubscibeView.subviews objectAtIndex:i] removeFromSuperview];
        }
        else{
            i++;
        }
    }
    for (NSInteger i=0; i<mySubscibeArray.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = [[[mySubscibeArray objectAtIndex:i] valueForKey:@"cid"] integerValue];
        [button setBackgroundImage:[UIImage imageNamed:@"subscribe_select@2x"] forState:UIControlStateNormal];
        [button setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button setTitle:[[mySubscibeArray objectAtIndex:i] valueForKey:@"catname"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(DeleteCustomSubscibeButton:) forControlEvents:UIControlEventTouchUpInside];
        
        NSInteger row = i/4;
        NSInteger col = i%4;
        CGFloat spaceing = (kScreenWidth - buttonWidth*4 - 30)/3;
        button.frame = CGRectMake(15 + (spaceing + buttonWidth)*col, kSystemSubscibeButtonSpacingToTop + (buttonHeight + 12)*row, buttonWidth, buttonHeight);
        [mySubscibeView addSubview:button];
        
        UIImageView *deleteImageview=[[UIImageView alloc]initWithFrame:CGRectMake(50, -10, 23, 23)];
        [button addSubview:deleteImageview];
        deleteImageview.image=[UIImage imageNamed:@"subscribe_delete"];
    }
    NSInteger totalRowForCustom = mySubscibeArray.count/4;
    if (mySubscibeArray.count%4) {
        totalRowForCustom += 1;
    }
    customTextField.frame = CGRectMake(customTextField.frame.origin.x, kCustomSubscibeButtonSpacingToTop + totalRowForCustom*(buttonHeight + 12) - 12 + kCustomSubscibeTextFieldSpacingToButton, customTextField.frame.size.width, customTextField.frame.size.height);
    mySubscibeView.frame = CGRectMake(mySubscibeView.frame.origin.x, systemSubscibeView.frame.origin.y + systemSubscibeView.frame.size.height, mySubscibeView.frame.size.width,  customTextField.frame.origin.y + customTextField.frame.size.height);
}

- (void)addOrDeleteSystemSubscibeButton:(UIButton *)sender{
    __block NSString *action = nil;
    __block NSInteger index = 0;
    [systemSubscibeArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (((SubscibeNameListModel *)[systemSubscibeArray objectAtIndex:idx]).cid == sender.tag) {
            if (((SubscibeNameListModel *)[systemSubscibeArray objectAtIndex:idx]).status == 1) {//已关注
                action = @"out";
            }
            else{//未关注
                action = @"join";
            }
            index = idx;
            
            *stop = YES;
        }
    }];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"cid":[NSString stringWithFormat:@"%ld",sender.tag],@"action":action};
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kAddOrDeleteSystemSubscibeURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
        }
        else{
            if ([action isEqualToString:@"out"]) {//退出成功
                ((SubscibeNameListModel *)[systemSubscibeArray objectAtIndex:index]).status = 0;
                [self reloadSystemSubscibeView];
            }
            else if ([action isEqualToString:@"join"]){//关注成功
                ((SubscibeNameListModel *)[systemSubscibeArray objectAtIndex:index]).status = 1;
                [self reloadSystemSubscibeView];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"网络无法连接，请检查网络" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alertView show];
    }];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [mainScrollView setContentOffset:CGPointMake(0, textField.frame.origin.y) animated:YES];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    if ([textField.text length] == 0) {
        return NO;
    }
    if ([textField.text length] > 5) {
        return NO;
    }
    [self addMySubscibeWithString:textField.text];

    textField.text = @"";

    return YES;
}

- (void)addMySubscibeWithString:(NSString *)addString{
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"people":@"0",@"catname":addString};
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kAddMySelfSubscibeURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
        }
        else{
            [mySubscibeArray addObject:[[SubscibeNameListModel alloc]initWithDict:[responseObject valueForKey:@"data"]]];
            [self reloadCustomSubscibeView];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"网络无法连接，请检查网络" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alertView show];
    }];
}

- (void)DeleteCustomSubscibeButton:(UIButton *)sender{
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"people":@"0",@"cid":[NSString stringWithFormat:@"%ld",sender.tag]};
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kDeleteMySelfSubscibeURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
        }
        else{
            [mySubscibeArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                if (((SubscibeNameListModel *)[mySubscibeArray objectAtIndex:idx]).cid == sender.tag) {
                    [mySubscibeArray removeObjectAtIndex:idx];
                    
                    [self reloadCustomSubscibeView];
                    
                    *stop = YES;
                }
            }];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"网络无法连接，请检查网络" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alertView show];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
